package com.xjggb.hellomail.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Component
public class MailService {
    @Autowired
    private JavaMailSender mailSender;
// 从配置文件中注入发件人的姓名
    @Value("${spring.mail.username}") //注入配置文件数据
    private String fromEmail;
    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 标题
     * @param content 正文
     * @throws
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
       // 发件人
        message.setFrom(fromEmail);
       //收件人
        message.setTo(to);
       //标题
        message.setSubject(subject);
       //正文
        message.setText(content);

        mailSender.send(message);

    }
    /**
     * 发送文本邮件
     * @param to 收件人
     * @param subject 标题
     * @param content 正文
     * @param  html,格式是否为html
     */

public void sendHtmlMail(String to, String subject, String content,boolean html) throws MessagingException {
//注意这里使用的是MimeMessage

        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper = new MimeMessageHelper(message, true);
    // 发件人
        helper.setFrom(fromEmail);
    //收件人
        helper.setTo(to);
    //标题
        helper.setSubject(subject);

//第二个参数：格式是否为html

        helper.setText(content, html);

        mailSender.send(message);

        }


}
